from Weapon import *
from direct.task import Task 
from panda3d.core import *
from direct.gui.OnscreenText import OnscreenText
from direct.actor.Actor import Actor
import random, sys, os, math

class Events():
     def __init__(self):
          funcMap = {"sys.exit":base.Exit,"self.OnceButton":self.OnceButton,"self.setKey": self.setKey,"self.setMbutton": self.setMbutton,
          "self.toggledebug":self.toggledebug,"self.togglewireframe":self.togglewireframe,"self.togglelighting":self.togglelighting,"self.toggletextures":self.toggletexture,
          "self.noclip":self.noclip}

          self.keyMap = {"A":0, "D":0, "W":0, "S":0,"space":0,"ctrl":0,"G":0,"R":0,"B":0,"K":0,"P":0}
          self.mousemap = {"m1":0,"m2":0,"m3":0}
          self.isNoCliping = False
          f = open("controls.xml", "r")
          text = f.readlines()
          for n in range(len(text)):
               newline = str(text[n]).replace("\n","").split(",")
               if len(newline) == 4:
                    list = [newline[2],int(newline[3])]
                    f = funcMap[newline[1]]
                    base.accept(newline[0],f,list)
               elif len(newline) == 2:
                    f = funcMap[newline[1]]
                    base.accept(newline[0],f)
               elif len(newline) == 5:
                    f = funcMap[newline[1]]
                    base.acceptonce(newline[0],f)
          base.win.setCloseRequestEvent("Alt-f4")
          base.accept("Alt-f4",base.Exit)
          base.accept("v", base.bufferViewer.toggleEnable)
          base.accept("V", base.bufferViewer.toggleEnable)
          base.bufferViewer.setPosition("llcorner")
          base.accept("window-event", self.WindowEvent)

     def handleEventGame(self,task):
          dt = globalClock.getDt()
          time = globalClock.getFrameTime()
          player = base.Player
          playergun = player.gunlist[player.equip[player.current]]
          BodyForward =  player.dummy.getMat().getRow3(1)
          CamForward = base.camera.getMat().getRow3(1)
          BodySide = player.dummy.getMat().getRow3(0)
          force = 0
          strafe = 0
          if base.Physics.pController.isOnGround():
               base.CamController.movespeed = 10
          elif self.isNoCliping:
               base.CamController.movespeed = 50
          else:
               base.CamController.movespeed = 4
          if (self.keyMap["space"]!=0):
               if base.Physics.pController.isOnGround():
                    base.Physics.pController.startJump()
          if (self.keyMap["W"]!=0):
               force = base.CamController.movespeed
          if (self.keyMap["S"]!=0):
               force = -base.CamController.movespeed
          if (self.keyMap["A"]!=0):
               strafe = -base.CamController.movespeed
          if (self.keyMap["D"]!=0):
               strafe = base.CamController.movespeed
          if (self.keyMap["R"]!=0):
               pass
          if (self.keyMap["G"]!=0):
               pass
          if (self.keyMap["B"]!=0):
               pass

     #---------------------------MOUSE------------------------------#
          if self.mousemap["m1"]!=0:
               player.gunlist[player.equip[player.current]].Fire()
          elif self.mousemap["m1"]== 0 and player.gunlist[player.equip[player.current]].automatic == False:
               player.gunlist[player.equip[player.current]].canfire = True
          if self.mousemap["m2"]!=0:
               pass
          if self.mousemap["m3"]!=0:
               pass
          if base.mouseWatcherNode.hasMouse():
               try:
                    x=base.mouseWatcherNode.getMouseX()
                    y=base.mouseWatcherNode.getMouseY()
                    move = [x,y]
                    base.CamController.heading -= move[0]*base.CamController.sensitivity
                    base.CamController.pitch += move[1]*base.CamController.sensitivity
                    base.win.movePointer(0, base.Centre[0], base.Centre[1])
                    base.CamController.Update()
               except:
                    print "Unexpected error:", sys.exc_info()[0]
     #-------------------------PHYSICS------------------------#
          dir = (Vec3(BodyForward)*force + Vec3(BodySide)*strafe)
          base.Physics.pController.setLinearMovement(dir)
          if base.Physics.OnLadder:
               base.Physics.pController.startFly()
          else:
               if base.Physics.pController.movementState == "flying":
                    base.Physics.pController.stopFly()
          if self.isNoCliping:
               base.Physics.pController.startFly()
          else:
               if base.Physics.pController.movementState == "flying":
                    base.Physics.pController.stopFly()
     #------------------------TIMERS--------------------------#
          if time - playergun.lastfired >= 0.05:
               playergun.offset = playergun.baseoffset
          if len(player.lastbullethit) > 1:
               if time - player.lastbullethit[1] >= 0.3:
                    if len(player.graphiclist) > 1:
                         del player.graphiclist[0]
                         del player.lastbullethit[0]
                         player.graphiclist[0].cleanup()
          return Task.cont

     def setKey(self, key, value):
          self.keyMap[key] = value
        
     def setMbutton(self,button,value):
          self.mousemap[button] = value
         
     def toggledebug(self):
          render.analyze()

     def togglewireframe(self):
          base.toggleWireframe()

     def togglelighting(self):
          pass
          #if not base.lighting:
          #     base.buffer.setActive(0)
          #     base.lighting = True
          #else:
          #     base.buffer.setActive(1)
          #     base.lighting = False

     def toggletexture(self):
          base.toggleTexture()

     def IsInView(self, object):
          lensBounds = base.cam.node().getLens().makeBounds()
          bounds = object.getBounds()
          bounds.xform(object.getParent().getMat(base.cam))
          return lensBounds.contains(bounds)

     def noclip(self):
          if self.isNoCliping:
               self.isNoCliping = False
          else:
               self.isNoCliping = True
            
     def findCenter(self):
          winX = base.props.getXSize()
          winY = base.props.getYSize()
          return [winX / 2, winY / 2]

     def OnceButton(self,key,value):
          if key == "Q":
               i = base.Player.lastwep
               base.Player.lastwep = base.Player.current
               base.Player.current = i
               base.Player.SetModel()
          if key == "1":
               if base.Player.current != 0:
                    base.Player.lastwep = base.Player.current
                    base.Player.current = 0
                    base.Player.SetModel()
          if key == "2":
               if base.Player.current != 1:
                    base.Player.lastwep = base.Player.current
                    base.Player.current = 1
                    base.Player.SetModel()
          if key == "3":
               if base.Player.current != 2:
                    base.Player.lastwep = base.Player.current
                    base.Player.current = 2
                    base.Player.SetModel()
     def WindowEvent(self,a=0):
          width = base.win.getProperties().getXSize()
          height = base.win.getProperties().getYSize()
          base.Centre = [width/2,height/2]
          base.cam.node().getLens().setFilmSize(width, height)
          # base.cam.node().getLens().setFocalLength(1000)
         
     def doEnter(self, triggerShape, otherShape):
          pass
     def doStay(self, triggerShape, otherShape):
          pass
     def doLeave(self, triggerShape, otherShape):
          pass
     def doDown(self, *args):
          pass